import {
    Controller,
    Get,
    Post,
    Body,
    Patch,
    Param,
    Delete,
    UseInterceptors,
    UploadedFiles,
    Req,
    BadRequestException,
} from '@nestjs/common';
import { Request } from '@common/auth';
import { PhotosService } from './photos.service';
import { CreatePhotoDto } from './dto/create-photo.dto';
import { UpdatePhotoDto } from './dto/update-photo.dto';
import { FilesInterceptor } from '@nestjs/platform-express';
import { ListPhotoDto } from './dto/list-photos.dto';
import { isMongoId } from 'class-validator';
import { ObjectId } from 'mongoose';

@Controller()
export class PhotosController {
    constructor(private readonly photosService: PhotosService) {}

    @Post('/photos/create')
    @UseInterceptors(FilesInterceptor('files'))
    create(
        @Body() createPhotoDto: CreatePhotoDto,
        @Req() req: Request,
        @UploadedFiles() files: Array<Express.Multer.File>
    ) {
        if (files.length === 0) {
            throw new BadRequestException('请上传图片！');
        }
        return this.photosService.create(createPhotoDto, req.user, files);
    }
    @Post('/photos/list')
    list(@Body() dto: ListPhotoDto) {
        if (!dto.where.user && !dto.where.photosType && !dto.where.keyword) {
            throw new BadRequestException('请选择用户或照片类型或关键词！');
        }
        return this.photosService.list(dto);
    }

    @Get('/photos/:id')
    findOne(@Param('id') id: ObjectId & string, @Req() req: Request) {
        if (!isMongoId(id)) {
            throw new BadRequestException('id错误！');
        }
        return this.photosService.findOne(id, req.user);
    }

    @Patch('/photos/:id')
    update(@Param('id') id: string, @Body() updatePhotoDto: UpdatePhotoDto) {
        return this.photosService.update(+id, updatePhotoDto);
    }

    @Delete('/photos/:id')
    remove(@Param('id') id: string) {
        return this.photosService.remove(+id);
    }
}
